package com.ny.until;

import com.ny.config.JwtConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类，用于生成和解析JWT Token
 */
@Component
public class JwtUtil {
    
    @Autowired
    private JwtConfig jwtConfig;
    
    private static JwtUtil jwtUtil;
    
    @PostConstruct
    public void init() {
        jwtUtil = this;
        jwtUtil.jwtConfig = this.jwtConfig;
    }
    
    /**
     * 生成JWT Token
     * @param username 用户名
     * @param userId 用户ID
     * @param role 用户角色
     * @return 生成的JWT Token字符串
     */
    public static String generateToken(String username, Integer userId, String role) {
        try {
            System.out.println("开始生成Token，参数: username=" + username + ", userId=" + userId + ", role=" + role);
            Date now = new Date();
            System.out.println("当前时间: " + now);
            Date expiryDate = new Date(now.getTime() + jwtUtil.jwtConfig.getExpiration());
            System.out.println("过期时间: " + expiryDate);
            
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", username);
            claims.put("role", role);
            System.out.println("Claims: " + claims);
            
            String token = Jwts.builder()
                    .setClaims(claims)
                    .setSubject(String.valueOf(userId))
                    .setIssuedAt(new Date())
                    .setExpiration(expiryDate)
                    .signWith(SignatureAlgorithm.HS256, jwtUtil.jwtConfig.getSecret())
                    .compact();
            System.out.println("生成的Token: " + token);
            return token;
        } catch (Exception e) {
            System.err.println("生成Token时发生异常: ");
            e.printStackTrace();
            throw e;
        }
    }
    
    /**
     * 解析JWT Token
     * @param token JWT Token字符串
     * @return Claims对象，包含Token中的信息
     */
    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(jwtUtil.jwtConfig.getSecret())
                .parseClaimsJws(token)
                .getBody();
    }
    
    /**
     * 从Token中获取用户ID
     * @param token JWT Token字符串
     * @return 用户ID
     */
    public static Integer getUserIdFromToken(String token) {
        Claims claims = parseToken(token);
        return Integer.valueOf(claims.getSubject());
    }
    
    /**
     * 验证Token是否有效
     * @param token JWT Token字符串
     * @return Token是否有效
     */
    public static boolean validateToken(String token) {
        try {
            Claims claims = parseToken(token);
            return !claims.getExpiration().before(new Date());
        } catch (Exception e) {
            return false;
        }
    }
}